package com.yzg.simple.netty.dubbo.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * @author misterWei
 * @create 2020年01月09号:23点47分
 * @mailbox mynameisweiyan@gmail.com
 *
 * 基于RPC 远程调用做出的服务端代码
 */
public class NettyRpcServer {

    public static void startServer(String hostName,int port){
        startServer0(hostName, port);
    }

    private static void startServer0(String hostName,int port){
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
              serverBootstrap.group(bossGroup,workerGroup)
                              .channel(NioServerSocketChannel.class)
                               .handler(new LoggingHandler(LogLevel.INFO))
                               /* .option(ChannelOption.SO_BACKLOG,128)
                                 .childOption(ChannelOption.SO_KEEPALIVE,true)*/
                                  .childHandler(new ChannelInitializer<SocketChannel>() {
                                      @Override
                                      protected void initChannel(SocketChannel ch) throws Exception {
                                          //加入编解码
                                          ChannelPipeline pipeline = ch.pipeline();
                                          pipeline.addLast(new StringDecoder());
                                          pipeline.addLast(new StringEncoder());
                                          //自定义handler
                                          pipeline.addLast(new NettyRpcServerHandler());

                                      }
                                  });
              //绑定地址
            serverBootstrap.bind(hostName, port).sync().channel().closeFuture().sync();

        }catch (Exception ex){
            ex.printStackTrace();
        }finally {
         bossGroup.shutdownGracefully();
         workerGroup.shutdownGracefully();
        }

    }

}
